package yunplus.io.hchome.presenter.implement;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import yunplus.io.hchome.display.view.ILaunchView;
import yunplus.io.hchome.model.storage.DomainShared;
import yunplus.io.hchome.presenter.contract.ILaunchPresenter;

/**
 * Created by yfsoft on 2016/12/16.
 */

public class LaunchPresenter implements ILaunchPresenter {

    private final static String TAG = "LaunchPresenter";

    protected Activity _mActivity;

    protected ILaunchView _mView;

    public LaunchPresenter(Activity activity, ILaunchView view) {
        _mActivity = activity;
        _mView = view;
    }

    @Override
    public void launch() {
        Log.d(TAG, "run launch");
        if(DomainShared.isSavedDomain(_mActivity)){
            Log.d(TAG, "start app");
            String domain = DomainShared.getDomain(_mActivity);
            String gateway = DomainShared.getGatewayType(_mActivity);
            _mView.startAppFromLan(domain, "lan".equals(gateway));
        }else{
            Log.d(TAG, "go login");
            _mView.goLoginWithWifi(isWifi());
        }
    }

    @Override
    public void checkNetwork() {
        _mView.checkNetworkStart();
        int network = getNetwork();
        switch(network){
            case ConnectivityManager.TYPE_WIFI:
                _mView.useWifi();
                return;
            case ConnectivityManager.TYPE_MOBILE:
                _mView.useMobile();
                return;
            case -1:
                _mView.unAvaliable();
        }
    }

    public int getNetwork(){
        ConnectivityManager connManager = (ConnectivityManager)_mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        if(networkInfo!= null) {
            int networkType = networkInfo.getType();
            return networkType;
        }
        return -1;
    }

    @Override
    public boolean isWifi() {
        if(ConnectivityManager.TYPE_WIFI == getNetwork()){
            return true;
        }
        return false;
    }

    @Override
    public boolean isMobile() {
        return ConnectivityManager.TYPE_MOBILE == getNetwork();
    }

    @Override
    public boolean unavaliable() {
        return !isWifi() && !isMobile();
    }
}
